package dyyx;

import java.io.File;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MiniHttpServer extends Thread {

	public static final String VERSION = "MiniHttpServer  http://codefun007.xyz/";

	public static final Map MIME_TYPES = new HashMap();

	private File _rootDir;

	private ServerSocket _serverSocket;

	private boolean _running = true;

	public MiniHttpServer(File paramFile, int paramInt) throws Exception {
		this._rootDir = paramFile.getCanonicalFile();
		if (!this._rootDir.isDirectory())
			throw new Exception("Not a directory.");
		this._serverSocket = new ServerSocket(paramInt);
		start();
	}

	public void run() {
		while (this._running) {
			try {
				Socket socket = this._serverSocket.accept();
				RequestHandleThread requestHandleThread = new RequestHandleThread(socket, this._rootDir);
				requestHandleThread.start();
			} catch (Throwable e) {
				System.out.println("run error,"+e);
			}
		}
	}

	public static String getExtension(File paramFile) {
		String str1 = "";
		String str2 = paramFile.getName();
		int i = str2.lastIndexOf(".");
		if (i >= 0) {
			str1 = str2.substring(i);
		}
		return str1.toLowerCase();
	}

	public static void main(String[] args) throws Exception {
		String rootdir = System.getProperty("rootdir");
		String port = System.getProperty("port");

		if (rootdir == null || rootdir.trim().length() <= 0) {
			rootdir = "./";
		}
		if (port == null || port.trim().length() <= 0) {
			port = "80";
		}

		int portint = Integer.parseInt(port);

		System.out.println("rootdir=" + rootdir + ",port=" + portint+","+new Date());

		MiniHttpServer simpleWebServer = new MiniHttpServer(new File(rootdir), portint);
	}

	static {
		String str1 = "image/";
		MIME_TYPES.put(".gif", str1 + "gif");
		MIME_TYPES.put(".jpg", str1 + "jpeg");
		MIME_TYPES.put(".jpeg", str1 + "jpeg");
		MIME_TYPES.put(".png", str1 + "png");
		String str2 = "text/";
		MIME_TYPES.put(".html", str2 + "html");
		MIME_TYPES.put(".htm", str2 + "html");
		MIME_TYPES.put(".txt", str2 + "plain");
	}


}
